<template>
  <div class="page-container">
    <van-nav-bar
      title="我要投诉"
      left-arrow
      @click-left="onClickLeft"
      class="bg-white border-b"
      fixed
      placeholder
    />

    <div class="content-wrapper">
      <van-search
        v-model="searchValue"
        placeholder="请输入您要投诉企业/商铺的名称"
        class="mt-4 mx-4"
        shape="round"
        clearable
        @input="handleSearchInput"
        @search="search"
        @click-left-icon="handleSearchIconClick"  
        @clear="handleClear"
        ref="searchInputRef"
      />

      <!-- 搜索结果下拉框 -->
      <div 
        v-if="showSearchResults" 
        class="search-dropdown mx-4"
      >
        <van-list>
          <div
            v-for="(item, index) in searchResults"
            :key="index"
            class="dropdown-item"
            @click="selectComplaint(item)"
          >
            {{ item.companyName }}
          </div>
        </van-list>
        <div v-if="searchResults.length === 0 && !loading" class="no-results">
          未找到相关企业
        </div>
      </div>

      <!-- 错误提示 -->
      <div v-if="showError" class="error-message px-4 mt-4">
        <van-notice-bar
          left-icon="warning"
          background="#fff2f0"
          color="#ff4d4f"
        >
          {{ errorMessage }}
        </van-notice-bar>
      </div>

      <!-- 历史投诉对象 -->
      <div v-if="!showSearchResults && !showError && historyComplaints.length > 0" class="mt-6 px-4">
        <div class="flex justify-between items-center mb-3">
          <h3 class="text-sm font-medium text-gray-500">历史投诉对象</h3>
          <span class="text-xs text-gray-400 cursor-pointer" @click="clearHistory">
            清空
          </span>
        </div>
        <div class="flex flex-wrap">
          <van-tag
            v-for="(item, index) in historyComplaints"
            :key="index"
            round
            type="primary"
            plain
            class="mr-2 mb-2 history-tag"
            @click="selectComplaint(item)"
          >
            {{ item.companyName }}
            <van-icon 
              name="cross" 
              class="ml-1 close-icon" 
              @click.stop="removeHistoryItem(item.companyName)"
            />
          </van-tag>
        </div>
      </div>

      <!-- 热门投诉对象 -->
      <div v-if="!showSearchResults && !showError" class="mt-6 px-4">
        <h3 class="text-sm font-medium text-gray-500 mb-3">热门投诉对象</h3>
        <van-list v-if="popularComplaints.length > 0">
          <van-cell
            v-for="(item, index) in popularComplaints"
            :key="index"
            :title="item.companyName"
            :value="`总投诉量${item.complaintCount}`"
            :left-icon="item.companyPicture"
            is-link
            @click="selectComplaint(item)"
          >
            <template #title>
              <div class="flex items-center flex-nowrap">
                <!-- 排名数字 -->
                <span class="rank-number" :class="getRankClass(index)">{{ index + 1 }}</span>
                <span class="company-name mx-2">{{ item.companyName }}</span>
                <!-- 前三名显示"热"字 -->
                <span v-if="index < 3" class="hot-tag">热</span>
                <van-icon
                  v-if="item.complaintCount > 20000" 
                  name="fire-o"
                  color="#FF4D4F"
                  class="ml-1"
                />
              </div>
            </template>
          </van-cell>
        </van-list>
        <div v-else class="text-center text-gray-400 py-4">
          暂无热门投诉对象
        </div>
      </div>

      <!-- 下一步按钮 - 只在未显示搜索结果和错误时显示 -->
      <div v-if="!showSearchResults && !showError" class="mt-8 px-4 mb-6 next-button-container">
        <van-button
          round
          block
          :color="hasSelectedCompany ? 'linear-gradient(to right, #ffd700, #ffb700)' : '#f5f5f5'"
          :class="['next-button', hasSelectedCompany ? 'next-button-active' : 'next-button-inactive']"
          @click="handleNextStep"
        >
          下一步
        </van-button>
      </div>
    </div>

    <!-- 清空历史记录确认对话框 -->
    <van-dialog
      v-model:show="showClearHistoryDialog"
      title="确认清空"
      message="确定要清空所有历史记录吗？"
      show-cancel-button
      confirm-button-text="确定"
      cancel-button-text="取消"
      @confirm="confirmClearHistory"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import { showToast, showConfirmDialog } from 'vant';
import { useRouter } from 'vue-router';
import { queryByCompanyName, hotCompanyList } from '@/api';

// 路由
const router = useRouter();

// 搜索框绑定值
const searchValue = ref('');
// 投诉对象
const company = ref({
  companyId: "",
  companyName: "",
});
// 搜索结果
const searchResults = ref([]);
// 加载状态
const loading = ref(false);
// 热门投诉对象数据
const popularComplaints = ref([]);
// 防抖定时器
let searchTimer = null;
// 控制清空历史记录对话框显示
const showClearHistoryDialog = ref(false);
// 搜索框引用
const searchInputRef = ref(null);
// 错误状态
const showError = ref(false);
const errorMessage = ref('');

// localStorage 键名
const HISTORY_KEY = 'complaint_history';
// 最大历史记录数量
const MAX_HISTORY_COUNT = 10;

// 计算属性：是否显示搜索结果
const showSearchResults = computed(() => {
  return searchValue.value.trim() !== '' && searchResults.value.length > 0;
});

// 计算属性：是否已选择投诉对象
const hasSelectedCompany = computed(() => {
  return company.value.companyName !== "";
});

// 历史投诉对象 - 从 localStorage 初始化
const historyComplaints = ref([]);

// 页面加载时获取热门投诉列表和初始化历史记录
onMounted(() => {
  fetchHotCompanies();
  loadHistoryComplaints();
});

// 从 localStorage 加载历史投诉对象
const loadHistoryComplaints = () => {
  try {
    const historyData = localStorage.getItem(HISTORY_KEY);
    if (historyData) {
      historyComplaints.value = JSON.parse(historyData);
    }
  } catch (error) {
    console.error('加载历史投诉对象失败:', error);
    historyComplaints.value = [];
  }
};

// 保存历史投诉对象到 localStorage
const saveHistoryComplaints = () => {
  try {
    localStorage.setItem(HISTORY_KEY, JSON.stringify(historyComplaints.value));
  } catch (error) {
    console.error('保存历史投诉对象失败:', error);
    showToast('保存历史记录失败');
  }
};

// 添加投诉对象到历史记录
const addToHistory = (companyObj) => {
  // 检查是否已存在
  const existingIndex = historyComplaints.value.findIndex(
    item => item.companyName === companyObj.companyName
  );

  if (existingIndex !== -1) {
    // 如果已存在，移动到最前面
    const existingItem = historyComplaints.value.splice(existingIndex, 1)[0];
    historyComplaints.value.unshift(existingItem);
  } else {
    // 如果不存在，添加到最前面
    historyComplaints.value.unshift({
      companyId: companyObj.companyId || "",
      companyName: companyObj.companyName
    });

    // 限制历史记录数量
    if (historyComplaints.value.length > MAX_HISTORY_COUNT) {
      historyComplaints.value = historyComplaints.value.slice(0, MAX_HISTORY_COUNT);
    }
  }

  // 保存到 localStorage
  saveHistoryComplaints();
};

// 从历史记录中删除单个项目
const removeHistoryItem = (companyName) => {
  const index = historyComplaints.value.findIndex(item => item.companyName === companyName);
  if (index !== -1) {
    historyComplaints.value.splice(index, 1);
    saveHistoryComplaints();
    showToast('已删除');
  }
};

// 清空历史记录
const clearHistory = () => {
  if (historyComplaints.value.length === 0) {
    showToast('暂无历史记录');
    return;
  }
  showClearHistoryDialog.value = true;
};

// 确认清空历史记录
const confirmClearHistory = () => {
  historyComplaints.value = [];
  saveHistoryComplaints();
  showToast('已清空历史记录');
  showClearHistoryDialog.value = false;
};

// 获取热门投诉对象
const fetchHotCompanies = async () => {
  try {
    const response = await hotCompanyList();
    if (response.company) {
      popularComplaints.value = response.company;
    } else {
      showToast('获取热门投诉对象失败');
    }
  } catch (error) {
    console.error('获取热门投诉对象出错:', error);
    showToast('获取热门投诉对象出错');
  }
};

// 返回按钮点击事件
const onClickLeft = () => {
  router.go(-1);
};

// 选择投诉对象
const selectComplaint = (companyObj) => {
  // 如果传入的是字符串（历史兼容），则转换为对象
  if (typeof companyObj === 'string') {
    company.value = {
      companyId: "",
      companyName: companyObj
    };
  } else {
    // 传入的是对象，直接赋值
    company.value = {
      companyId: companyObj.companyId,
      companyName: companyObj.companyName
    };
  }
  
  searchResults.value = []; // 清空搜索结果
  showError.value = false; // 隐藏错误提示
  
  // 添加到历史记录
  addToHistory(company.value);
};

// 搜索输入处理（带防抖）
const handleSearchInput = () => {
  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  
  // 如果搜索值为空，清空搜索结果和错误提示
  if (searchValue.value.trim() === '') {
    searchResults.value = [];
    showError.value = false;
    return;
  }
  
  // 设置新的定时器，延迟500ms执行搜索
  searchTimer = setTimeout(() => {
    search();
  }, 500);
};

// 搜索图标点击事件
const handleSearchIconClick = () => {
  // 清除防抖定时器，立即执行搜索
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  search();
};

// 清除搜索框内容
const handleClear = () => {
  searchResults.value = []; // 清空搜索结果
  showError.value = false; // 隐藏错误提示
  
  // 清除防抖定时器
  if (searchTimer) {
    clearTimeout(searchTimer);
    searchTimer = null;
  }
};

// 搜索函数
const search = async () => {
  if (searchValue.value.trim() === '') {
    searchResults.value = [];
    showError.value = false;
    return;
  }
  
  loading.value = true;
  showError.value = false; // 重置错误状态
  
  try {
    const response = await queryByCompanyName(searchValue.value);
    if (response.company) {
      searchResults.value = response.company;
      if (searchResults.value.length === 0) {
        // 不再显示toast，在下拉框中显示"未找到相关企业"
      }
    } else {
      searchResults.value = [];
    }
  } catch (error) {
    console.error('搜索出错:', error);
    searchResults.value = [];
    
    // 根据错误类型设置错误提示
    if (error.message === '公司未找到') {
      errorMessage.value = `未找到与"${searchValue.value}"相关的企业，请检查输入是否正确`;
      showError.value = true;
    } else {
      errorMessage.value = '搜索失败，请稍后重试';
      showError.value = true;
      showToast('搜索失败');
    }
  } finally {
    loading.value = false;
  }
};

// 获取排名样式类
const getRankClass = (index) => {
  if (index === 0) return 'rank-first';
  if (index === 1) return 'rank-second';
  if (index === 2) return 'rank-third';
  return 'rank-other';
};

// 下一步按钮点击事件
const handleNextStep = () => {
  // 检查是否选择了投诉对象
  if (!hasSelectedCompany.value) {
    // 使用showConfirmDialog提示选择投诉对象
    showConfirmDialog({
      title: '提示',
      message: '请先选择投诉对象',
      confirmButtonText: '去选择',
      cancelButtonText: '取消',
    }).then(() => {
      // 确认后聚焦搜索框
      focusSearchInput();
    }).catch(() => {
      // 取消操作
    });
    return;
  }
  
  // 跳转到投诉申请页面，携带公司信息
  router.push({
    name: 'complaintApplication',
    query: {
      merchantName: company.value.companyName,
      merchantId: company.value.companyId
    }
  });
};

// 聚焦搜索输入框
const focusSearchInput = () => {
  nextTick(() => {
    if (searchInputRef.value && searchInputRef.value.focus) {
      searchInputRef.value.focus();
    }
  });
};
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.content-wrapper {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px; /* 为底部导航栏留出空间 */
}

.border-b {
  border-bottom: 1px solid #f5f5f5;
}

/* 排名数字样式 */
.rank-number {
  font-size: 14px;
  font-weight: bold;
  flex-shrink: 0;
  margin-right: 8px;
}

/* 第1名样式 */
.rank-first {
  color: #ff4d4f;
}

/* 第2名样式 */
.rank-second {
  color: #ff7a45;
}

/* 第3名样式 */
.rank-third {
  color: #ffa940;
}

/* 其他名次样式 */
.rank-other {
  color: #666;
}

/* 公司名称样式 */
.company-name {
  flex-shrink: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 60%;
}

/* 热标签样式 */
.hot-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 3px;
  font-size: 10px;
  font-weight: bold;
  line-height: 1;
  flex-shrink: 0;
  margin-left: 4px;
}

/* 下一步按钮基础样式 */
.next-button {
  width: calc(100% - 32px);
  margin: 0 auto;
  height: 44px;
  font-size: 16px;
  font-weight: bold;
  border: none;
}

/* 激活状态的下一步按钮 */
.next-button-active {
  color: #333;
}

/* 未激活状态的下一步按钮 */
.next-button-inactive {
  color: #ccc;
  background-color: #f5f5f5;
}

/* 历史记录标签样式 - 修改为白底黑字 */
.history-tag {
  position: relative;
  padding: 6px 10px; /* 调整内边距，增加宽度 */
  margin: 4px; /* 调整外边距，缩短边框长度 */
  background-color: white;
  color: #333;
  border: 1px solid #ebedf0;
  border-radius: 16px; /* 保持圆角 */
  font-size: 14px;
}

.close-icon {
  font-size: 12px;
  color: #999;
  cursor: pointer;
  margin-left: 4px;
}

.close-icon:hover {
  color: #666;
}

/* 搜索结果下拉框样式 */
.search-dropdown {
  position: absolute;
  top: 120px; /* 根据实际布局调整位置 */
  left: 16px;
  right: 16px;
  background: white;
  border: 1px solid #ebedf0;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
}

/* 下拉框选项样式 */
.dropdown-item {
  padding: 12px 16px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}

.dropdown-item:last-child {
  border-bottom: none;
}

.dropdown-item:hover {
  background-color: #f8f9fa;
}

/* 无结果提示样式 */
.no-results {
  padding: 12px 16px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* 错误提示样式 */
.error-message {
  margin-top: 16px;
}

/* 下一步按钮容器 */
.next-button-container {
  margin-bottom: 80px; /* 确保按钮在底部导航栏上方有足够空间 */
}
</style>